package com.hippoframework.config;


import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import cn.hutool.core.map.MapUtil;
import cn.hutool.setting.dialect.Props;
import com.hippoframework.utils.PropsUtil;
import com.hippoframework.utils.StringUtils;
import lombok.Getter;

/**
 * @author TylerW
 * @date 4/30/2020 2:27 PM
 */
public class Environment {

    /**
     * 配置分类缓存
     */
    @Getter
    private final Set<GenericProps> config = new HashSet<>(32);

    /**
     * 主配置
     * key: path
     */
    @Getter
    private final Map<Object, Object> summaryProps = new HashMap<>(32);

    private String profile = ConfigConstants.DEFAULT_PROFILE_NAME;

    public void addGenericProps(GenericProps props) {
        config.add(props);
        this.mergeIntoSummary(props.getProps());
    }

    private void mergeIntoSummary(Props props) {
        Set<Map.Entry<Object, Object>> entries = props.entrySet();
        for (Map.Entry<Object, Object> entry : entries) {
            summaryProps.put(entry.getKey(), entry.getValue());
        }
    }

    public void loadProfile() {
        String profile = this.getString(ConfigConstants.PROFILE_PATH);
        if (StringUtils.isNotBlank(profile)) {
            this.profile = profile;
        }
        Props profileProps = PropsUtil.load(ConfigConstants.DEFAULT_CONFIG_FILE + "_" + profile + ".properties");
        if (profileProps != null) {
            addGenericProps(new GenericProps(profileProps, PropsType.APP, ConfigConstants.PROFILE_CONFIG_NAME));
        }
    }

    public String getString(String key) {
        return MapUtil.getStr(summaryProps, key);
    }


}
